<template>
    <span>
        <Button @click="search" type="primary" icon="md-paper">征信报告：{{creditScore}}</Button>
        <Span v-if="queryFlag"/>
    </span>
</template>
<script>

    import {queryCreditCustInfo} from "../../../../api/afs-case/infomationDetail/applyCustomerDetail";

    Date.prototype.format = function (fmt) {
        let o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (let k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

    export default {
        name: "credit-pboc",
        props:{
            creditScore:{
                type:String,
                default:" / / " // 征信解读分，玄武返回，格式：主借人 / 共借人 / 担保人
            },
            applyNo:{
                type:String,
                default:""
            },
            type:{
                type:String,
                default:"1" // 默认常规审批，查询客户信息表 否则传 2 查询预审信息表
            }
        },
        data() {
            return {
                ws: null,
                socketIp: '127.0.0.1', // 本机中间件
                socketPort: '21381',    // 中间件端口
                customerInfo: {
                    applicationName: "",
                    applicationType: "1", // 主借人
                    cardNo: ""
                }
            }
        },
        computed:{
            queryFlag(){
                if(this.applyNo){
                    this.queryMainCustomer();
                }
                return true;
            }
        },
        beforeDestroy() {
            if(this.ws){
                this.ws.close();
            }
        },
        methods: {
            search(){
                //预览征信报告
                if(!this.ws){
                    this.openSocket();
                }
                console.log(this.customerInfo);
                let _this = this;
                setTimeout(() => {
                    _this.searchOrPreview(2);
                }, 500);
            },
            createSocket(onSuccess) {
                let _this = this;
                let url = `ws://${this.socketIp}:${this.socketPort}`;
                this.ws = new WebSocket(url);
                this.ws.onopen = function () {
                    console.log('connected成功');
                    if (onSuccess)
                        onSuccess();
                };
                this.ws.onmessage = function (response) {
                    console.log('服务器返回' + response.data);
                    let jsonData;
                    try {
                        jsonData = JSON.parse(response.data);
                    } catch (e) {
                        _this.$Message.error("解析服务端返回结果失败！");
                        return;
                    }
                    let type = jsonData.Type.toUpperCase();
                    switch (type) {
                        case 'CONNOK':
                            console.log('登录成功');
                            break;
                        case 'CONNFAIL':
                            console.log('登录失败');
                            break;
                        case 'SEARCH_OK':
                            console.log('查询成功');
                            break;
                        case 'SEARCH_FAIL':
                            _this.processSearchFail(jsonData);
                            break;
                        default:
                            _this.$Message.error('解析服务端响应类型失败！');
                    }
                };
                this.ws.onclose = function (e) {
                    _this.$Message.error('链接断开');
                };
                this.ws.onerror = function (e) {
                    _this.$Message.error('传输中发生异常');
                }
            },
            processSearchFail(jsonData) {
                console.log(`查询失败,错误码：${jsonData.Result},Msg:${jsonData.Msg}`);
                if (jsonData.Result - 0 == -10) {
                    let op = function (dialogResult) {
                        if (dialogResult == false)
                            return;

                        //预览征信报告
                        this.searchOrPreview(2);
                    };
                    this.$Modal.confirm({
                        title: "查询失败",
                        content: "查询失败,是否预览该客户的历史征信报告?",
                        onOk: () => {
                            op(true);
                        }
                    })
                } else {
                    this.$Message.error(jsonData.Msg);
                }
            },
            conn() {
                let token = this.$store.getters.access_token;
                if (this.ws.readyState != 1) {
                    console.log('socket未连接');
                    return;
                } else {
                    this.ws.send(`CONN {"USERNAME":"${this.$store.state.user.userInfo.username}","TOKEN":"${token}","SYSTYPE": "1"}`);
                }
            },
            getBirthdayFromIdCard(idCard) {
                let birthday = "";
                if (idCard != null && idCard != "") {
                    if (idCard.length == 15) {
                        birthday = "19" + idCard.substr(6, 6);
                    } else if (idCard.length == 18) {
                        birthday = idCard.substr(6, 8);
                    }
                    birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
                }
                return birthday;
            },
            getInfoByCard(card) {
                let sex = '', birth = '', valid = false;
                if (card.length == 15) {
                    sex = ((card[14] + 0) % 2 == 0) ? 'M' : 'F';
                    birth = this.getBirthdayFromIdCard(card);
                    valid = true;
                } else if (card.length == 18) {
                    sex = ((card[17] + 0) % 2 == 0) ? 'M' : 'F';
                    birth = this.getBirthdayFromIdCard(card);
                    valid = true;
                }
                return {sex: sex, birth: birth, valid: valid};
            },
            getCommonSearchData(obj, filter) {
                let _this = this;
                filter = filter || [];
                let now = new Date().format("yyyy-MM-dd hh:mm:ss"); //时间
                obj.application_no = "DS_" + new Date().getTime();//申请号随机生成（以便于服务端唯一识别）
                obj.application_date = now;//申请日期
                obj.capoperator = this.$store.state.user.userInfo.username;//信贷专员用户ID
                obj.queryreason = '02';//查询理由
                obj.infos = [];

                let checkResult = true;
                filter.forEach(function (value, index) {
                    let applicant_name = value['applicant_name']; // 姓名
                    let applicant_type = value['applicant_type']; // 类型 1 主借人 2 共借人 3 担保人
                    let card_no = value['card_no'];

                    let cardInfo = _this.getInfoByCard(card_no);
                    if (!cardInfo.valid) {
                        _this.$Message.error("身份证号码格式不正确");
                        checkResult = false;
                        return;
                    }

                    obj.infos.push({
                        applicant_name: applicant_name,
                        card_type: '0', //固定值
                        card_no: card_no,
                        applicant_type: applicant_type,
                        sex: cardInfo.sex,
                        birth: cardInfo.birth,
                    });
                });
                return checkResult;
            },
            searchOrPreview(type) {
                let _this = this;
                let applicant_name = this.customerInfo.applicationName; //申请日期
                let card_no = this.customerInfo.cardNo; //身份证号
                let applicant_type = this.customerInfo.applicationType;// 客户身份
                if (!(applicant_name && card_no && applicant_type)) {
                    _this.$Message.error('请完善征信查询条件');
                    return;
                }
                /** 根据身份证获取性别、生日 **/
                let obj = {};
                let result = this.getCommonSearchData(obj, [{
                    applicant_name: applicant_name,
                    card_no: card_no,
                    applicant_type: applicant_type
                }]);

                if (!result) return;

                let searchJson = JSON.stringify(obj);
                if (this.ws.readyState != 1) {
                    console.log('socket未连接');
                    return;
                } else {
                    if (type == 1)
                        this.ws.send(`Search ${searchJson}`);
                    else
                        this.ws.send(`Preview ${searchJson}`);
                }
            },
            openSocket() {
                this.createSocket(this.conn);
            },
            queryMainCustomer() {
                let params = {
                    applyNo: this.applyNo,
                    type: this.type
                }
                queryCreditCustInfo(params).then(res => {
                    if (res.code == "0000") {
                        this.customerInfo.applicationName = res.data.custName;
                        this.customerInfo.cardNo = res.data.certNo;
                    }
                })
            }
        }
    }
</script>

<style scoped>

</style>
